﻿
ko.bindingHandlers["load-library"] = {

    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {

		var update = function () {

			ko.applyBindingsToDescendants(
				bindingContext.createChildContext(
					ViewModel.Metadata[valueAccessor()].CreateInstance()
				,	null//valueAccessor()
				,	function (context) {

						ko.utils.extend(context, valueAccessor());
					}
				)
			,	element
			);
		};

		if (!ViewModel.Metadata[valueAccessor()])

			$.getScript(
				"/App_ClientScripts/Model/" + valueAccessor() + ".js"
			,	update
			);

		else update();

        return { controlsDescendantBindings: true };
    }
};

var _TemplatesCache = { };

ko.bindingHandlers["load-template"] = {

    init: ko.bindingHandlers.template.init,

    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {

		var options = valueAccessor();

		if (!_TemplatesCache[options.name()])
		{
			$(element).text("Loading...");
			$.get(
				"App_ClientTemplates/" + options.name() + "-Template.html"
			)
			.success(
				function (e)
				{
					$("body").append(e);

					_TemplatesCache[options.name()] = true;

					ko.bindingHandlers.template.update(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
				}
			)
			.error(
				function (e)
				{
					alert("Failed loading the template [" + options.name() + "]!");
				}
			);
		}
		else return ko.bindingHandlers.template.update.apply(this, arguments);
	}
};